<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <!--编写Ant Design组件，组件需要在官方文件查找修改使用-->
      <a-form layout="inline">
        <a-row :gutter="[16,24]">
          <a-col :span="6">
            <a-form-item label="账号:">
              <a-input placeholder="请输入账户" v-model="queryParam.userId" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="合格证编号:">
              <a-input placeholder="请输入合格证编号" v-model="queryParam.code" allowClear></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :span="6">
              <a-form-item label="主体名称:">
                <a-input placeholder="请输入主体名称" v-model="queryParam.companyName" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="产品名称:">
                <a-input placeholder="请输入产品名称" v-model="queryParam.productName" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <Area :query-param="queryParam"></Area>
            </a-col>
            <a-col :span="6">
              <a-form-item label="检验机构:">
                <a-input placeholder="请输入检验机构" v-model="queryParam.testBy" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="检测方式:">
                <JDictSelectTag dictCode="unit_type" v-model="queryParam.testType"></JDictSelectTag>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开发日期:">
                <j-date v-model="queryParam.startDate"></j-date>
                <j-date v-model="queryParam.endDate"></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="6">
            <a-button type="primary" icon="search" @click="loadUser">
              查询
            </a-button>
            <a-button type="primary" icon="reload" style="margin-left: 8px">
              重置
            </a-button>
            <a @click="handleToggleSearch" style="margin-left: 8px">
              {{ toggleSearchStatus ? '收起' : '展开' }}
              <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form>


      <a-table :scroll="{x:true}"
               :columns="columns"
               :pagination="ipagination"
               :dataSource="dataSource"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               rowKey="id"
               @change="handleTableChange"
               :loading="loading">

        <template slot="fileSlot" slot-scope='text'>
          <span v-if='!text || text.trim() ===""' style='font-size: 12px;font-style: italic;'>无文件</span>
          <span v-else-if='isImage(text)'>
            <img @click='imgClickView(text)' :src='getImgView(text)' height='25px' alt=''
                 style='max-width:80px;font-size: 12px;font-style: italic;cursor: pointer;'/>
            <!--多图片点击预览组件-->
            <duo-image-viewer :list="imgSrcList" @update:show="handleClose" :show="showViewer"
                              :currentIndex="currentIndex"/>
          </span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadClick(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a>编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a>详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>

    </div>
  </a-card>
</template>

<script>
  //定义引入的js插件
  import ACol from "ant-design-vue/es/grid/Col";
  import ARow from "ant-design-vue/es/grid/Row";
  import Area from "../../../components/njt/Area";
  // import {getDictItemsFromCache} from "../../../api/api";
  import JDate from "../../../components/jeecg/JDate";
  import AFormModelItem from "ant-design-vue/es/form-model/FormItem";
  import AFormItem from "ant-design-vue/es/form/FormItem";
  import {getAction} from '@/api/manage';
  import {filterDictTextByCache} from '@/components/dict/JDictSelectUtil'

  export default {
    components: {AFormItem, AFormModelItem, JDate, Area, ARow, ACol},
    data() {
      return {
        //定义组件中关联属性
        queryParam: {
          pageNum: 1,
          pageSize: 3,
        },
        loading: false,
        tableDate: [],
        unittypelist: [],
        toggleSearchStatus: false,
        columns: [
          {
            title: '账号',
            align: "center",
            dataIndex: 'mobilePhone'
          },
          {
            title: '生产主体',
            align: "center",
            dataIndex: 'companyName'
          },
          {
            title: '法人姓名',
            align: "center",
            dataIndex: 'legalPersonName'
          },
          {
            title: '省',
            align: 'center',
            dataIndex: 'province'
          },
          {
            title: '市',
            align: 'center',
            dataIndex: 'city'
          },
          {
            title: '区/县',
            align: 'center',
            dataIndex: 'area'
          },
          {
            title: '乡镇/街道',
            align: 'center',
            dataIndex: 'country'
          },
          {
            title: '详细地址',
            align: 'center',
            dataIndex: 'detailAddress'
          },
          {
            title: '生产地址',
            align: "center",
            dataIndex: 'produceAddress'
          },
          {
            title: '产品名称',
            align: "center",
            dataIndex: 'productName'
          },
          {
            title: '重量(数量)',
            align: "center",
            dataIndex: 'productWeight'
          },
          {
            title: '单位',
            align: "center",
            dataIndex: 'unit',
            customRender: (text) => {
              // 字典值翻译通用方法
              return filterDictTextByCache('unit_type1', text)
            }
          },

          {
            title: '检测方式',
            align: "center",
            dataIndex: 'testType',
          },
          {
            title: '检验机构',
            align: "center",
            dataIndex: 'testBy'
          },
          {
            title: '检测报告',
            align: "center",
            dataIndex: 'testReport',
            scopedSlots: {customRender: 'fileSlot'}
          },
          {
            title: '开具日期',
            align: "center",
            dataIndex: 'createTime'
          },
          {
            title: '合格证编号',
            align: "center",
            dataIndex: 'code'
          },
          {
            title: '打印次数',
            align: "center",
            dataIndex: 'printNumber'
          },

          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        dataSource: [],
        selectedRowKeys: [],
        selectedRows: [],
        currentIndex: 0, // 打开图片查看器时，需要定位到的图片的索引
        imgSrcList: [], // 图片查看器数据集
        showViewer: false, // 是否打开图片查看器
      }
    },
    methods: {
      //定义组件事件关联方法
      loadUser() {
        console.log(this.queryParam)
      },
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus;
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      handleTableChange(pagination) {
        //将新的分页条数据赋值给原数据对象（这样才能实现页码选中切换）
        this.ipagination = pagination;
        //再次请求数据
        this.queryParam.pageNum = pagination.current;
        this.queryParam.pageSize = this.ipagination.pageSize;
        this.loadCertificate();
      },
      loadCertificate() {
        var url = "/njt-certificate/list"
        getAction(url, this.queryParam).then((res) => {
          // 在原生开发中获取后端响应数据是通过：res.data
          // 为什么现在不使用data就可以获取到后端响应数据
          // 原因：就是因为有响应拦截器，拦截器中已经处理了，将后端响应对象数据获取传入参数res
          console.log(res)
          if (res.success) {
            this.msg = res.result;
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
          }
          this.loading = false;
        })
      },
      imgClickView(text) {
        // 将图片路径处理一下
        let srcArray = text.split(",")
        let srcAllArray = []
        srcArray.forEach((temp) => {
          srcAllArray.push(this.getImgView(temp))
        })
        this.imgSrcList = srcAllArray;
        this.showViewer = !this.showViewer
      },
      // 多图片查看器打开
      handleOpen() {
        this.showViewer = !this.showViewer
      },
      // 多图片查看器关闭
      handleClose() {
        this.showViewer = false
      },
      //解决数据库存储多张图片，表格默认显示第一张
      getImgView(text) {
        if (text && text.indexOf(",") > 0) {
          text = text.substring(0, text.indexOf(","))
        }
        return text;
      },
      // 判断是否是图片
      isImage(path) {
        const imgFormat = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
        for (let j = 0; j < imgFormat.length; j++) {
          if (path.lastIndexOf(imgFormat[j]) > -1) {
            return true
          }
        }
        return false
      },
// 官方默认的downloadFile方法只能打开单个文件，但是项目实际需求中可能会存在同时多个pdf，所以需要重新定义downloadClick方法
// pdf下载点击事件
      downloadClick(text) {
        let arrays = text.split(',')
        // 打开多个pdf
        for (let i = 0; i < arrays.length; i++) {
          // 直接在浏览器窗口打开
          window.open(arrays[i])
        }
      },

    },
    created() {//页面加载前执行的操作
      this.loadCertificate()
    }
  }
</script>